<?php


namespace App\Http\Controllers\FddVerifySDK;

use App\Http\Controllers\common\LMReturn;
use App\Models\User;
use App\Models\ContractModel;
use App\Models\Order;
use App\Models\SystemCompanyMessage;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use App\Http\Controllers\BranchUtils;

include_once 'Fdd.Api.php';
include_once 'Fdd.Data.php';
include_once 'Fdd.Encryption.php';

class FddUserUtils
{
    // 普通用户注册
    public static function FddUserRegistered($user_id, $account_type='1') {
        $params = new \FddAccount();
        $params->SetAccountType($account_type);
        $params->SetOpenID($user_id);
        return \FddApi::registerAccount($params);
    }

    // 普通用户实名认证
    public static function FddUserVerify($customer_id, $verified_way, $page_modifyh, $user_name, $customer_ident_type, $cert_type, $customer_ident_no, $mobile, $ident_path, $cert_flag) {
        $params = new \FddCertification();
        $params->SetNotifyUrl(env('COMMON_NOTIFY') . '/FddVerify/NotifyUrl');
        $params->SetCustomerID($customer_id);
        $params->SetVerifiedWay($verified_way);
        $params->SetPageModify($page_modifyh);
        // 客户名称
        $params->SetCustomerName($user_name);
        // 是否支持其他证件类型
        $params->SetCustomerIdentType($customer_ident_type);
        // 客户身份证号
        if ($customer_ident_no != null) {
            $params->SetCustomerIdentNo($customer_ident_no);
        }
        // 客户电话
        $params->SetMobile($mobile);
        // 客户身份证正面地址
        if ($ident_path != null) {
            $params->SetIdentFrontPath($ident_path);
        }
        // 证件类型
        $params->SetCertType($cert_type);
        // 是否认证成功后自动申请实名证书
        $params->SetCertFlag($cert_flag);
        return \FddApi::getPersonVerifyUrl($params);
    }

    // 用户实名认证回调时查询实名认证信息做对比
    public static function CompareUserMessage($transaction_no, $user_id) {
        $parames = new \FddCertification();
        $parames->SetVerifiedVSerialNo($transaction_no);
        $result = \FddApi::FindPersonCertInfo($parames);
        if ($result['code'] == 1) {
            $user = User::find($user_id);
            if ($user->name != $result['data']['person']['personName']) {
                return false;
            }
            if ($result['data']['person']['certType'] == 0) {
                if ($user->id_type != 1) {
                    return false;
                }
            } else {
                if ($user->id_type == 1) {
                    return false;
                }
            }
            if ($result['data']['person']['idCard'] != $user->id_number) {
                return false;
            }
            if ($result['data']['person']['mobile'] != $user->contact_manner) {
                return false;
            }
        } else {
            return false;
        }
        return true;
    }

    // 企业实名认证
    public static function FddCompanyVerify($company_id) {
        $company = SystemCompanyMessage::find($company_id);
        if ($company) {
            $company_no = $company->company_no;
            $company_tel = $company->legal_mobile;
            $customer_id = self::FddUserRegistered($company_no, '2');
            $company->customer_id = $customer_id['data'];
            $params = new \FddCertification();
            $params->SetCustomerID($customer_id['data']);
            $params->SetPageModify('1');
            $params->SetCertFlag('1');
            $params->SetNotifyUrl(env('COMMON_NOTIFY') . '/FddVerify/CompanyNotifyUrl');
            $result = \FddApi::getCompanyVerifyUrl($params);
            if ($result['code'] == 1) {
                $transaction_no = $result['data']['transactionNo'];
                $company->transaction_no = $transaction_no;
                $company->save();
                $url = $result['data']['url'];
                return self::SendMassage(base64_decode($url), $company_tel, 2);
            } else {
                return $result;
            }
        } else {
            return LMReturn::Error('缺少系统信息，请联系系统管理员');
        }
    }

    // 更新企业实名认证信息
    public static function UploadCompanyMessage($serialNo) {
        $company = SystemCompanyMessage::where('transaction_no', $serialNo)->first();
        $params = new \FddCertification();
        $params->SetVerifiedVSerialNo($serialNo);
        $result = \FddApi::FindCompanyCertInfo($params);
        if ($result['code'] == 1) {
            $related_transaction_no = $result['data']['company']['relatedTransactionNo'];
            $verify_type = $result['data']['company']['verifyType'];
            $company_name = $result['data']['company']['companyName'];
            $organization = $result['data']['company']['organization'];
            $organization_path = $result['data']['company']['organizationPath'];
            $legal_name = $result['data']['company']['legalName'];
            $legal = $result['data']['company']['legal'];
            $reg_form_path = $result['data']['company']['regFormPath'];
            $status = $result['data']['company']['status'];
            $company_email = $result['data']['company']['companyEmail'];
            $certificates_type = $result['data']['company']['certificatesType'];
            if (isset($result['data']['manager'])) {
                $legal_mobile = $result['data']['manager']['mobile'];
                $company->legal_mobile = $legal_mobile;
            }
            if (isset($result['data']['bankCard'])) {
                $bank_name = $result['data']['bankCard']['BankName'];
                $bank_detail_name = $result['data']['bankCard']['bankDetailName'];
                $bank_card_no = $result['data']['bankCard']['bankCardNo'];
                $branch_bank_code = $result['data']['bankCard']['branchBankCode'];
                $province_name = $result['data']['bankCard']['provinceName'];
                $city_name = $result['data']['bankCard']['cityName'];
                $company->bank_name = $bank_name;
                $company->bank_detail_name = $bank_detail_name;
                $company->bank_card_no = $bank_card_no;
                $company->branch_bank_code = $branch_bank_code;
                $company->province_name = $province_name;
                $company->city_name = $city_name;
            }
            $company->related_transaction_no = $related_transaction_no;
            $company->verify_type = $verify_type;
            $company->company_name = $company_name;
            $company->organization = $organization;
            $company->organization_path = $organization_path;
            $company->legal_name = $legal_name;
            $company->legal = $legal;
            $company->reg_form_path = $reg_form_path;
            $company->status = $status;
            $company->company_email = $company_email;
            $company->certificates_type = $certificates_type;
            $company->remark = '企业信息已实名认证';
        } else {
            $company->remark = '回调查询时发生错误：'.$result['msg'];
        }
        $company->save();
    }

    // 上传合同模板
    public static function FddContractModel($model_id, $filePath) {
        $params = new \FddTemplate();
        $params->SetContract_template_id($model_id);
        $CURLFile = new \CURLFile(realpath($filePath));
        $params->SetFile($CURLFile);
        $result = \FddApi::UploadTemplateDocs($params);
        if ($result['code'] == 1) {
            return LMReturn::Success();
        } else {
            return $result;
        }
    }

    // 编辑合同模板
    public static function UploadTemplate($model_id) {
        $param = new \FddTemplate();
        $param->SetContract_template_id($model_id);
        $url = \FddApi::GetDocStream($param);
        return ['code'=>200, 'msg'=>'成功', 'data'=>$url];
    }

    // 上传不可修改的合同模板
    public static function FddContractAbleModel($model_id, $filePath) {
        $params = new \FddTemplate();
        $params->SetTemplate_id($model_id);
        $CURLFile = new \CURLFile(realpath($filePath));
        $params->SetFile($CURLFile);
        $result = \FddApi::UploadTemplate($params);
        if ($result['code'] == 1) {
            return LMReturn::Success();
        } else {
            return $result;
        }
    }

    // 查看合同模板接口
    public static function SeleContract($template_id) {
        $params = new \FddTemplate();
        $params->SetTemplate_id($template_id);
        return \FddApi::ViewTemplate($params);
    }

    // 删除合同模板接口
    public static function DeleteContract($template_id) {
        $params = new \FddTemplate();
        $params->SetTemplate_id($template_id);
        return \FddApi::TemplateDelete($params);
    }

    // 下载合同模板
    public static function DownloadContract($template_id) {
        $params = new \FddTemplate();
        $params->SetTemplate_id($template_id);
        $result = \FddApi::DownloadTemplate($params);
        $file_name = 'P' . time() . '.pdf';
        $path = public_path('pdf_files/' . date("Ymd"));
        File::makeDirectory($path, 0777, true, true);
        $file = fopen('../public/pdf_files/'.date("Ymd").'/'.$file_name, "w");
        fwrite($file, $result);
        $exists = Storage::disk('new_ftp')->put('htdocs/pdf_files/' . date("Ymd") . '/' . $file_name, file_get_contents('../public/pdf_files/' . date("Ymd") . '/' . $file_name));
        $file_url = env("FTP2_URL") . 'pdf_files/' . date("Ymd") . '/' . $file_name;
        if ($exists) {
            return ['code'=>200, 'data'=>$file_url, 'msg'=>'success'];
        } else {
            return LMReturn::Error('网络错误，请重试');
        }
    }

    // 模板填充界面地址
    public static function FileContractUrl($template_id, $contract_id) {
        $template = ContractModel::find($template_id);
        if ($template) {
            $template_name = $template->title;
            $params = new \FddTemplate();
            $params->SetContract_template_id($template_id);
            $params->SetContract_id($contract_id);
            $params->SetDoc_title($template_name);
            return \FddApi::FillPage($params);
        } else {
            return LMReturn::Error('没有该模板');
        }
    }

    // 单个合同查询/下载
    public static function CheckContract($contract_id, $type) {
        $params = new \FddContractManageMent();
        $params->SetContract_id($contract_id);
        if ($type == 1) {
            $result = \FddApi::ViewContract($params);
        } else {
            $result = \FddApi::DownLoadContract($params);
        }
        $data['url'] = $result;
        return LMReturn::Success($data);
    }

    // 获取合同模板填充域表单
    public static function GetKeys($template_id) {
        $params = new \FddTemplate();
        $params->SetTemplate_id($template_id);
        $params->SetFile_type(1);
        return \FddApi::GetPdftemplateKeys($params);
    }

    // 模板填充
    public static function FileContract($parameter_map, $template_id, $order_id) {
        $template = ContractModel::find($template_id);
        $params = new \FddTemplate();
        $params->SetDoc_title($template->title);
        $params->SetTemplate_id($template_id);
        $params->SetContract_id($order_id);
        $params->SetFile_type(1);
        $params->SetParameter_map(json_encode($parameter_map, true));
        return \FddApi::GenerateContract($params);
    }

    // 发送短信短链接方法
    public static function SendMassage($source_url, $mobile, $message_type) {
        $params = new \SmsParam();
        $params->SetSource_url($source_url);
        $mobileStr = bin2hex(openssl_encrypt($mobile, "des-ede3", \FddConfig::AppSecret, 1));
        $params->SetMobile($mobileStr);
        $params->SetExpire_time(4320);
        $params->SetMessage_type(1);
        $params->SetSms_template_type($message_type);
        $result = \FddApi::PushShortUrlSms($params);
        if ($result['code'] == 1) {
            return ['code'=>200, 'msg'=>'短信通知已发送给客户'];
        } else {
            return $result;
        }
    }

    // 手动签署接口
    public static function ExtsignWay($order_id) {
        $order = Order::where('id', $order_id)->with('user')->with('contract_model')->first();
        try {
            if ($order) {
                $fdd_status = $order['user']['fdd_status'];
                $fdd_cert_status = $order['user']['fdd_cert_status'];
                if ($fdd_status != 2 || $fdd_cert_status != 1) {
                    return LMReturn::Error('该用户并未实名认证，无法进行电子签约');
                }
                $customer_id = $order['user']['customer_id'];
                $mobile = $order['user']['contact_manner'];
                $doc_title = $order['contract_model']['title'];
            } else {
                return LMReturn::Error('未找到该订单');
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('订单或客户信息不全，请先补全订单或客户信息');
        }
        $notigy_url = env('COMMON_NOTIFY') . '/FddVerify/SignNotify';
        $params = new \FddSignContract();
        $transaction_id = time() . str_pad($order['user_id'], 7, STR_PAD_LEFT);
        $sta = FddUtils::FddRecordSave(1, $transaction_id, $order_id);
        if ($sta == 0) {
            return LMReturn::Error('获取交易流水号失败，请重试');
        }
        $params->SetTransaction_id($transaction_id);
        $params->SetContract_id($order['order_no']);
        $params->SetCustomer_id($customer_id);
        $params->SetNotify_url($notigy_url);
        $params->SetDoc_title($doc_title);
        $params->SetRead_time(10);
        $result = \FddApi::Extsign($params);
        if(isset($result['code'])) {
            return $result;
        } else {
            return self::SendMassage($result, $mobile, 1);
        }
    }

    // 合同归档
    public static function ContractFiling($order_id) {
        $order = Order::find($order_id);
        if ($order->fdd_sign_status != 1) {
            return LMReturn::Error('合同未签署完成，无法归档');
        }
        $params = new \FddContractManageMent();
        $params->SetContract_id($order['order_no']);
        $result = \FddApi::ContractFiling($params);
        if ($result['code'] == 1000) {
            $order->contract_file = 1;
            $order->save();
            return LMReturn::Success();
        } else {
            return ['msg'=>$result['msg'], 'code'=>$result['code']];
        }
    }

    // 自动归档
    public static function AdoutContractFiling($order_id) {
        $order = Order::find($order_id);
        $params = new \FddContractManageMent();
        $params->SetContract_id($order['order_no']);
        $result = \FddApi::ContractFiling($params);
        if ($result['code'] == 1000) {
            return 1;
        } else {
            return 0;
        }
    }

    // 企业签署
    public static function CompanyExtsign($order_id, $type) {
        $order = Order::where('id', $order_id)->with('contract_model')->first();
        try {
            if ($order) {
                $doc_title = $order['contract_model']['title'];
                $branch = $order['president_id'];
            } else {
                return LMReturn::Error('未找到该订单');
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('订单未绑定合同模板');
        }
        if ($type == 1) {
            $record_type = 2;
            if (env('COMPANY') == 3) {
                if ($branch == '国逸') {
                    $sys_id = 2;
                } elseif ($branch == '安盛') {
                    $sys_id = 3;
                } elseif ($branch == '逸盛') {
                    $sys_id = 4;
                } elseif ($branch == null) {
                    $sys_id = 1;
                } else {
                    $sys_id = BranchUtils::selePbranch($order['branch_id']);
                }
            } else {
                $sys_id = 1;
            }
        } else {
            $record_type = 3;
            $sys_id = 7;
        }
        $company = SystemCompanyMessage::find($sys_id);
        $notigy_url = env('COMMON_NOTIFY') . '/FddVerify/SignNotify';
        $params = new \FddSignContract();
        $transaction_id = time() . str_pad($order_id, 7, STR_PAD_LEFT);
        $sta = FddUtils::FddRecordSave($record_type, $transaction_id, $order_id);
        if ($sta == 1) {
            $params->SetTransaction_id($transaction_id);
            $params->SetContract_id($order['order_no']);
            $params->SetCustomer_id($company['customer_id']);
            $params->SetNotify_url($notigy_url);
            $params->SetDoc_title($doc_title);
            return \FddApi::Extsign($params);
        } elseif ($sta == 2) {
            return ['code'=>'300', 'msg'=>'改签署已完成，请勿重复签署'];
        } else {
            return ['code'=>'300', 'msg'=>'获取交易流水号失败请重试'];
        }
    }

    // 查询证书信息方法
    public static function CheckCertMessage($customer_id) {
        $app_id = \FddConfig::AppId;
        $timestamp = date('YmdHis');
        $sha1Str = strtoupper(sha1(\FddConfig::AppSecret . $customer_id));
        $msg_digest = base64_encode(strtoupper(sha1($app_id . strtoupper(md5($timestamp)) . $sha1Str)));
        $url = \FddConfig::FddServer . '/query_cert.api?app_id='.$app_id.'&timestamp='.$timestamp.'&v=2.0&msg_digest='.$msg_digest.'&customerId='.$customer_id;
        return \FddApi::https_request($url);
    }

    // 电子文件签署出证专业接口
    public static function OutPutCert($order_id) {
        $order = Order::find($order_id);
        try {
            $params = new \ComplianceContractReport();
            $params->SetAppId(\FddConfig::AppId);
            $params->SetContractNum($order->order_no);
            return \FddApi::ComplianceContractReport($params);
        } catch (\Throwable $th) {
            return LMReturn::Error('无此订单');
        }

    }

}
